import logging
from datetime import datetime
from typing import Literal

from fastapi import APIRouter, Query, Path
from fastapi.params import Depends
from pydantic import Field, validator, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

data_sql_api = APIRouter(prefix="/SqlApi", tags=["SqlApi"], dependencies=[Depends(get_db)])


class ChargeConfirmUpdate(BaseModel):
    """收费预存确认请求参数"""
    datatable: Literal["m_tc_dailyaccount", "m_tc_charge_head"] = Field(...,
                                                                        description="数据表名，可选值：m_tc_dailyaccount(收费预存)，m_tc_charge_head(收费单)")
    fbillno: str = Field(..., description="单据编号")
    type: str = Field(..., description="操作类型")


@data_sql_api.post("/statusUpdate", summary="收费预存．确认　接口")
def sql_api(charge: ChargeConfirmUpdate, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    try:
        datatable = charge.datatable
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            param = {"userid": user_id, "fbillno": charge.fbillno}
            # 收费预存．确认
            if (datatable.lower() == "m_tc_dailyaccount"):
                sql = "update m_tc_dailyaccount set fstate=1,fupddate=now(),foperator= :userid where fbillno= :fbillno "
            # 收费单．确认
            if (datatable.lower() == "m_tc_charge_head"):
                sql = "update m_tc_charge_head set fbillstate=2,fcheckdate=now(),fcheckuser= :userid where fbillno= :fbillno "
            db.execute(text(sql), param)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
